<template>
  <div class="roles-root">
    <!-- 0.导航 -->
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2、卡片视图 -->
    <el-card class="box-card">
      <!-- 添加按钮 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 2、角色列表 :data绑定数据 -->
      <el-table :data="pageInfo.list" border style="width: 100%" :header-cell-style="headerCellStyle">
        <el-table-column type="expand" label="展开" width="100">
          <template v-slot="scope">
            <el-row
              :class="[index1 === 0 ? 'bd-t' : '', 'bd-b', 'center-fx']"
              v-for="(item1, index1) in scope.row.children"
              :key="index1"
            >
              <!-- 左边的一级分类的列 -->
              <el-col :span="6">
                <el-tag closable @close="deleteRightById(scope.row, item1.id)"> {{ item1.authName }} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 右边的二级分类的列 -->
              <el-col :span="18">
                <!-- 二级权限再分成左右列 -->
                <el-row
                  :class="[index2 !== 0 ? 'bd-t' : '', 'center-fx']"
                  v-for="(item2, index2) in item1.children"
                  :key="index2"
                >
                  <el-col :span="6">
                    <el-tag closable type="success" @close="deleteRightById(scope.row, item2.id)"
                      >{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="index3"
                      @close="deleteRightById(scope.row, item3.id)"
                      >{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="200" align="center"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" width="200" align="center"></el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showUpdateDialog(scope.row)"
              >修改</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRole(scope.row)">删除</el-button
            ><el-button type="warning" icon="el-icon-setting" size="mini" @click="showRightsDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 3、分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pagenum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="pageInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination>
    </el-card>
    <!-- 3、添加用户对话框 @close="addRoleDialogClose()" 对话框关闭的操作  -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="7rem" @close="addRoleDialogClose()">
      <!-- 添加用户的表单 -->
      <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="updateRoleDialogVisible" width="7rem" @close="handleUpdateRoleClose()">
      <!-- 修改角色的表单 -->
      <el-form :model="updateRoleForm" :rules="addRoleRules" ref="updateRoleFromRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="updateRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDesc">
          <el-input v-model="updateRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 5、权限对话框 -->
    <el-dialog title="赋予权限" :visible.sync="rightDialogVisible" width="50%" @close="handleRightsDialogClose">
      <!-- 权限的树形结构 -->
      <el-tree
        :data="rightsList"
        node-key="id"
        :props="props"
        show-checkbox
        default-expand-all
        @check-change="handleCheckChange"
        ref="rightsTree"
        :default-checked-keys="defKeys"
      >
        <!--
          :data="rightsList" 树形解构绑定的数据源
          show-checkbox 是否显示checkbox
          node-key="id" checkbox选中时，选中的值是rightsList中权限对象的id属性
          :default-checked-keys="defKeys" 显示默认选中的权限checkbox
          :default-expand-all="true" 是否展开所有的权限列表
          :props="rightTreeProps" 树形解构渲染数据的属性
          ref="rightsTree" 当前树形结构元素的引用，便于查找当前元素
        -->
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '../../utils/request.js'
export default {
  data() {
    return {
      //1、所有角色列表
      roleList: [],
      //2、分页信息
      pageInfo: {
        pagenum: 1,
        pagesize: 5,
        total: 0,
        list: [],
        start: 0,
        end: 0,
        totalpage: 0
      },
      //3、表头的样式
      headerCellStyle: {
        backgroundColor: '#409EFF',
        color: '#ffffff',
        textAlign: 'center'
      },
      //4、控制添加角色对话框是否显示的标记
      addRoleDialogVisible: false,
      //5、添加用户表单对应的数据源
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      //6、添加用户的表单验证规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      },
      //修改角色表单数据源
      updateRoleForm: {
        id: 0,
        roleName: '',
        roleDesc: ''
      },
      //控制修改对话框显示的操作
      updateRoleDialogVisible: false,
      defKeys: [121, 104],
      //12、树形控件的配置
      props: {
        //树形控件显示的内容
        label: 'authName',
        //权限的下级权限列表
        children: 'children'
      },
      //11、tree结构的rights列表
      rightsList: [],
      //10、控制分配权限对话框是否显示
      rightDialogVisible: false,
      //9、分配权限的角色id
      roleId: 0
    }
  },
  methods: {
    //一页几条发生变化时，重新加载数据
    handleSizeChange(pagesize) {
      this.pageInfo.pagesize = pagesize
      this.getRoleList()
    },
    //页码发生变化时，重新加载数据
    handleCurrentChange(pagenum) {
      this.pageInfo.pagenum = pagenum
      this.getRoleList()
    },
    //1、获得角色列表信息
    async getRoleList() {
      let option = {
        type: 'get',
        url: 'roles'
      }
      let { data: res } = await request(option)
      console.log(res)
      this.roleList = res.data
      //计算总条数
      this.pageInfo.total = this.roleList.length
      //计算总页数
      this.pageInfo.totalpage = Math.ceil(this.pageInfo.total / this.pageInfo.pagesize)
      //计算起点
      let start = (this.pageInfo.pagenum - 1) * this.pageInfo.pagesize
      //计算终点
      let end = start + this.pageInfo.pagesize
      if (end > this.pageInfo.total) {
        end = this.pageInfo.total
      }
      //截取数组元素
      let arr = this.roleList
      this.pageInfo.list = []
      for (let i = start; i < end; i++) {
        this.pageInfo.list.push(arr[i])
      }
    },
    //4、根据角色id删除指定id权限
    async deleteRightById(role, rightId) {
      console.log(role, rightId)
      let confirm = await this.$confirm('确定要永久删除吗？', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消删除',
        type: 'warning'
      }).catch(e => e)
      if (confirm !== 'confirm') {
        return this.$message.info('取消删除')
      }
      let option = {
        url: `roles/${role.id}/rights/${rightId}`,
        type: 'delete'
      }
      let { data: res } = await request(option)
      //判断是否删除成功，重新加载数据
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('删除成功')
      //给role的children属性，重新赋值
      role.children = res.data
    },
    //5.添加角色
    addRole() {
      //表单验证
      let form = this.$refs['addRoleFormRef']
      form.validate(async valid => {
        if (!valid) {
          return this.$message.error('请正确填写用户信息')
        }
        let option = {
          url: 'roles',
          type: 'post',
          data: this.addRoleForm
        }
        let { data: res } = await request(option)
        console.log(res)
        //添加失败
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        //添加成功
        this.$message.success('添加成功')
        //关闭对话框
        this.addRoleDialogVisible = false
        //重新加载数据
        this.getRoleList()
      })
    },
    //5、添加用户对话框关闭时触发的事件
    addRoleDialogClose() {
      console.log('addRoleDialogClose')
      //找到表单
      let form = this.$refs['addRoleFormRef']
      //重置表单
      form.resetFields()
    },
    //6.删除角色
    async delRole(role) {
      console.log(role)
      if (!role) {
        return
      }
      //确认框 confirmRes=cancel/confirm
      let confirmRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定删除',
        //点击取消会抛出异常
        cancelButtonText: '取消删除',
        type: 'warning'
      }).catch(e => e)
      console.log(confirmRes)
      //如果点击的是取消，提示你取消了删除 this.$message.info("")
      if (confirmRes === 'cancel') {
        return this.$message.info('你取消了删除操作')
      }

      //如果点击是确定，执行用户删除操作，提示删除是否成功的消息this.$message.error("")/this.$message.success("")
      if (confirmRes === 'confirm') {
        let option = {
          url: 'roles/' + role.id,
          type: 'delete'
        }
        let { data: res } = await request(option)
        console.log(res)
        this.$message.success('删除成功')
      }
      //重新加载页面的数据
      this.getRoleList()
    },
    //7、修改对话框关闭时触发的操作
    handleUpdateRoleClose() {
      let form = this.$refs['updateRoleFromRef']
      //重置表单
      form.resetFields()
    },
    //8.点击显示修改对话框
    showUpdateDialog(role) {
      //user的属性全部赋值给this.editUserForm
      Object.assign(this.updateRoleForm, role)
      this.updateRoleDialogVisible = true
    },
    //9.修改角色信息
    updateRole() {
      let form = this.$refs['updateRoleFromRef']
      form.validate(async v => {
        if (!v) {
          return this.$message.error('请正确填写角色信息')
        }
        let option = {
          type: 'put',
          url: `roles/${this.updateRoleForm.id}`,
          data: this.updateRoleForm
        }
        let { data: res } = await request(option)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('修改成功')
        //隐藏对话框
        this.updateRoleDialogVisible = false
        //重新加载数据
        this.getRoleList()
      })
    },
    //15、获得当前角色的三级分类权限的id，也可以3层for实现
    getDefaultKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getDefaultKeys(item, arr)
      })
    },
    //14、checkbox变换时触发的函数
    handleCheckChange() {
      //console.log(this.defKeys)
      let tree = this.$refs['rightsTree']
      let arr = [...tree.getHalfCheckedKeys(), ...tree.getCheckedKeys()]
      console.log(arr)
    },
    //13、分配权限
    async grantRights() {
      let tree = this.$refs['rightsTree']
      let arr = [...tree.getHalfCheckedKeys(), ...tree.getCheckedKeys()]
      let options = {
        url: `roles/${this.roleId}/rights`,
        type: 'post',
        data: { rids: arr.join(',') }
      }
      let { data: res } = await request(options)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('分配权限成功')
      this.rightDialogVisible = false
      this.getRoleList()
    },
    //12、分配权限对话框关闭时触发的函数
    handleRightsDialogClose() {
      this.defKeys = []
    },
    //11、点击赋予权限按钮执行的操作
    async showRightsDialog(role) {
      //保存roleid
      this.roleId = role.id
      //获得当前role的三级权限数据
      //this.defKeys = []
      this.getDefaultKeys(role, this.defKeys)
      //请求权限数据
      let options = {
        url: 'rights/tree',
        type: 'get'
      }
      let { data: res } = await request(options)
      this.rightsList = res.data
      console.log(this.rightsList)
      //显示对话框
      this.rightDialogVisible = true
    }
  },
  mounted() {
    this.getRoleList()
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 0.1rem;
}
.bd-t {
  border-top: 1px solid #ddd;
}
.bd-b {
  border-bottom: 1px solid #ddd;
}
</style>
